package mapx

//
// 根据提供的keyMap，删除a的键值
// 只要存在对应的键，不管是什么值都删除
// isDeleteKeyMap 会同时删除keyMap中的键
func DeleteByKeyMap(a, keyMap map[string]interface{}, isDeleteKeyMap bool) (deleteMap map[string]interface{}) {
	if keyMap == nil {
		return
	}
	deleteMap = map[string]interface{}{}
	deleteByKeyMap(a, keyMap, isDeleteKeyMap, deleteMap)
	return
}

func deleteByKeyMap(a, keyMap map[string]interface{}, isDeleteKeyMap bool, deleteMap map[string]interface{}) {
	for keyKey, ikeyVal := range keyMap {
		if ikeyVal == nil { // 值为nil的时候需要删除
			deleteMap[keyKey] = a[keyKey]
			delete(a, keyKey)
			if isDeleteKeyMap {
				delete(keyMap, keyKey)
			}
			continue
		}
		switch keyVal := ikeyVal.(type) {
		case map[string]interface{}: // 如果是map, 表示不删除当前层, 只删除下一层
			iaVal, has := a[keyKey]
			if !has { // a的键值不存在，表示已经被删除，不需要处理
				continue
			}
			if keyVal == nil { // 值为nil的时候需要删除
				deleteMap[keyKey] = a[keyKey]
				delete(a, keyKey)
				if isDeleteKeyMap {
					delete(keyMap, keyKey)
				}
				continue
			}
			aVal, ok := iaVal.(map[string]interface{})
			if !ok { // a的键值必须为 map[string]interface{}
				panic("a[" + keyKey + "] not map")
			}
			if aVal == nil { // a的键值为nil，不需要遍历下一层
				continue
			}

			deleteMapField := map[string]interface{}{}
			deleteMap[keyKey] = deleteMapField
			deleteByKeyMap(aVal, keyVal, isDeleteKeyMap, deleteMapField)
			if len(aVal) == 0 {
				delete(a, keyKey)
			}
			if isDeleteKeyMap {
				if len(keyVal) == 0 {
					delete(keyMap, keyKey)
				}
			}

		default: // 否则, 删除当前
			deleteMap[keyKey] = a[keyKey]
			delete(a, keyKey)
			if isDeleteKeyMap {
				delete(keyMap, keyKey)
			}
		}
	}
	return
}
